export function getURLPath(): string {
  const { pathname, search, hash } = window.location;
  return pathname + search + hash;
}

export function getTimeText(): string {
  const time: Date = new Date();
  const text = `${time.getFullYear()}-${time.getMonth() + 1}-${time.getDate()} ${time.getHours()}:${time.getMinutes()}:${time.getSeconds()}:${time.getMilliseconds()}`;
  return text;
}

export function querySelectorAll(name: string): Element[] {
  return Array.prototype.slice.call(document.querySelectorAll(name));
}

export function debounce(fn: Function, wait: number): MutationCallback {
  let timeout: number = 0;
  let mutationsList: MutationRecord[] = [];
  return function (mrList: MutationRecord[]) {
    mutationsList = mutationsList.concat(mrList);
    if (timeout) clearTimeout(timeout);
    timeout = window.setTimeout(() => {
      fn.apply(null, [mutationsList]);
      mutationsList = [];
    }, wait);
  };
}

export function isJSON(text: string): boolean {
  if (text.slice(0, 1) === '{' && text.slice(-1) === '}') return true;
  return false;
}

export function getAttrVal(node: Element, attr: string): string | null {
  return node.getAttribute(attr);
}

export function getUrlParam(name: string) {
  const reg: RegExp = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
  const r: RegExpMatchArray | null = window.location.search.substr(1).match(reg);
  if (r != null) {
    return decodeURIComponent(r[2]);
  }
  return null;
}

export function isUrlDebug(): boolean {
  if (typeof window === 'object') {
    return getUrlParam('debug') === 'true';
  }
  return false;
}

// 复杂对象合并
export const mergeObj = (target: { [key: string]: any } = {}, source: { [key: string]: any } = {}) => {
  // eslint-disable-next-line no-restricted-syntax
  for (const key of Object.keys(source)) {
    if (source[key] instanceof Object) Object.assign(source[key], mergeObj(target[key], source[key]));
  }
  Object.assign(target, source);
  return target;
};

export default {
  isJSON,
  debounce,
  mergeObj,
  isUrlDebug,
  getAttrVal,
  getUrlParam,
  getTimeText,
  getURLPath,
  querySelectorAll,
};
